package com.basic.common.utils;

import com.basic.common.constant.CacheConstants;
import com.basic.common.core.domain.entity.SysUserInfo;
import com.basic.common.core.redis.RedisCacheUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户工具类
 */
public class UserUtils {

    /**
     * 获取用户缓存信息
     */
    public static List<SysUserInfo> getUserCache(){
        return RedisCacheUtils.getCacheObject(CacheConstants.USER_REDIS_KEY);
    }

    /**
     * 根据用户编号获取用户昵称
     */
    public static Object getNickNameByUserCode(String userCode){
        List<SysUserInfo> datas = getUserCache();
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }

        for (SysUserInfo data : datas) {
            if (StringUtils.equals(data.getUserCode(), userCode)) {
                return data.getNickName();
            }
        }
        return userCode;
    }

    /**
     * 根据用户编号获取用户id
     */
    public static Object getUserIdByUserCode(String userCode){
        List<SysUserInfo> datas = getUserCache();
        if (StringUtils.isNull(datas))
        {
           return StringUtils.EMPTY;
        }

        for (SysUserInfo data : datas) {
            if (StringUtils.equals(data.getUserCode(), userCode)) {
                return data.getUserId();
            }
        }
        return userCode;
    }

    /**
     * 根据用户id获取昵称
     */
    public static String getNickNameByUserId(String userIds){
        List<SysUserInfo> datas = getUserCache();
        if (StringUtils.isNull(datas)) {
            return StringUtils.EMPTY;
        }

        List<Long> userIdList = Arrays.stream(userIds.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());

        List<String> nickNames = datas.stream()
                .filter(data -> userIdList.contains(data.getUserId()))
                .map(SysUserInfo::getNickName)
                .collect(Collectors.toList());
        return String.join(",", nickNames);
    }

    /**
     * 根据用户id获取手机号
     */
    public static String getMobileByUserId(String userIds){
        List<SysUserInfo> datas = getUserCache();
        if (StringUtils.isNull(datas))
        {
            return StringUtils.EMPTY;
        }

        List<Long> userIdList = Arrays.stream(userIds.split(","))
                .map(Long::valueOf)
                .collect(Collectors.toList());

        List<String> mobiles = datas.stream()
                .filter(data -> userIdList.contains(data.getUserId()))
                .map(SysUserInfo::getUserName)
                .collect(Collectors.toList());
        return String.join(",", mobiles);
    }

}
